package com.chushouya.product.rabbitmq.listener;

import com.chushouya.common.dto.QueueMessage;
import com.chushouya.product.rabbitmq.sender.SuhuishouSyncMessageSender;
import com.chushouya.product.service.sync.SuhuishouSyncService;
import com.general.framework.core.exception.BaseException;
import com.general.framework.core.exception.ViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 速回收同步消息监听器
 * 监听速回收品牌和产品同步消息，调用相应的同步服务
 * 
 * @author system
 */
@Component
@Slf4j
public class SuhuishouSyncMessageListener {

    @Resource(name = "productSuhuishouSyncService")
    private SuhuishouSyncService suhuishouSyncService;

    /**
     * 监听速回收品牌同步消息
     */
    @RabbitListener(queuesToDeclare = @Queue(name = "chushouya.suhuishou.brand.sync", durable = "true"))
    public void handleBrandSyncMessage(QueueMessage<?> queueMessage) {
        log.info("收到速回收品牌同步消息: messageId={}, messageType={}, data={}", 
                queueMessage.getMessageId(), queueMessage.getMessageType(), queueMessage.getData());
        
        try {
            // 验证消息数据
            if (queueMessage.getData() == null) {
                log.error("速回收品牌同步消息数据为空: messageId={}", queueMessage.getMessageId());
                log.warn("数据为空的消息已处理，避免重复处理: messageId={}", queueMessage.getMessageId());
                return;
            }
            
            // 获取分类ID
            Long categoryId = extractCategoryId(queueMessage.getData());
            if (categoryId == null) {
                log.error("无法从消息中提取分类ID: messageId={}, data={}", 
                        queueMessage.getMessageId(), queueMessage.getData());
                log.warn("无效分类ID消息已处理，避免重复处理: messageId={}", queueMessage.getMessageId());
                return;
            }
            
            // 验证分类ID有效性
            if (categoryId <= 0) {
                log.error("分类ID无效: categoryId={}, messageId={}", categoryId, queueMessage.getMessageId());
                log.warn("无效分类ID消息已处理，避免重复处理: messageId={}", queueMessage.getMessageId());
                return;
            }
            
            log.info("开始处理速回收品牌同步，分类ID: {}, messageId: {}", categoryId, queueMessage.getMessageId());
            
            // 调用品牌同步服务
            suhuishouSyncService.syncBrand(categoryId);
            
            log.info("速回收品牌同步处理完成，分类ID: {}, messageId: {}", categoryId, queueMessage.getMessageId());
            
        } catch (ViolationException e) {
            log.error("速回收品牌同步消息验证错误: {}, messageId: {}", e.getMessage(), queueMessage.getMessageId());
            log.warn("验证异常消息已处理，避免重复处理: messageId={}", queueMessage.getMessageId());
        } catch (BaseException e) {
            log.error("速回收品牌同步消息业务异常: {}, messageId: {}", e.getMessage(), queueMessage.getMessageId());
            log.warn("业务异常消息已处理，避免重复处理: messageId={}", queueMessage.getMessageId());
        } catch (Exception e) {
            log.error("处理速回收品牌同步消息异常: {}, messageId: {}", e.getMessage(), queueMessage.getMessageId(), e);
            log.warn("异常消息已处理，避免重复处理: messageId={}", queueMessage.getMessageId());
        }
    }

    /**
     * 监听速回收产品同步消息
     */
    @RabbitListener(queuesToDeclare = @Queue(name = "chushouya.suhuishou.product.sync", durable = "true"))
    public void handleProductSyncMessage(QueueMessage<?> queueMessage) {
        log.info("收到速回收产品同步消息: messageId={}, messageType={}, data={}", 
                queueMessage.getMessageId(), queueMessage.getMessageType(), queueMessage.getData());
        
        try {
            // 验证消息数据
            if (queueMessage.getData() == null) {
                log.error("速回收产品同步消息数据为空: messageId={}", queueMessage.getMessageId());
                log.warn("数据为空的消息已处理，避免重复处理: messageId={}", queueMessage.getMessageId());
                return;
            }
            
            // 提取产品同步消息
            SuhuishouSyncMessageSender.SuhuishouProductSyncMessage syncMessage = 
                extractProductSyncMessage(queueMessage.getData());
            
            if (syncMessage == null) {
                log.error("无法从消息中提取产品同步信息: messageId={}, data={}", 
                        queueMessage.getMessageId(), queueMessage.getData());
                log.warn("无效产品同步消息已处理，避免重复处理: messageId={}", queueMessage.getMessageId());
                return;
            }
            
            // 验证分类ID和品牌ID有效性
            if (syncMessage.getCategoryId() == null || syncMessage.getCategoryId() <= 0) {
                log.error("分类ID无效: categoryId={}, messageId={}", syncMessage.getCategoryId(), queueMessage.getMessageId());
                log.warn("无效分类ID消息已处理，避免重复处理: messageId={}", queueMessage.getMessageId());
                return;
            }
            
            if (syncMessage.getBrandId() == null || syncMessage.getBrandId() <= 0) {
                log.error("品牌ID无效: brandId={}, messageId={}", syncMessage.getBrandId(), queueMessage.getMessageId());
                log.warn("无效品牌ID消息已处理，避免重复处理: messageId={}", queueMessage.getMessageId());
                return;
            }
            
            log.info("开始处理速回收产品同步，分类ID: {}, 品牌ID: {}, messageId: {}", 
                    syncMessage.getCategoryId(), syncMessage.getBrandId(), queueMessage.getMessageId());
            
            // 调用产品同步服务
            suhuishouSyncService.syncProduct(syncMessage.getCategoryId(), syncMessage.getBrandId());
            
            log.info("速回收产品同步处理完成，分类ID: {}, 品牌ID: {}, messageId: {}", 
                    syncMessage.getCategoryId(), syncMessage.getBrandId(), queueMessage.getMessageId());
            
        } catch (ViolationException e) {
            log.error("速回收产品同步消息验证错误: {}, messageId: {}", e.getMessage(), queueMessage.getMessageId());
            log.warn("验证异常消息已处理，避免重复处理: messageId={}", queueMessage.getMessageId());
        } catch (BaseException e) {
            log.error("速回收产品同步消息业务异常: {}, messageId: {}", e.getMessage(), queueMessage.getMessageId());
            log.warn("业务异常消息已处理，避免重复处理: messageId={}", queueMessage.getMessageId());
        } catch (Exception e) {
            log.error("处理速回收产品同步消息异常: {}, messageId: {}", e.getMessage(), queueMessage.getMessageId(), e);
            log.warn("异常消息已处理，避免重复处理: messageId={}", queueMessage.getMessageId());
        }
    }

    /**
     * 从消息数据中提取分类ID
     * 
     * @param data 消息数据
     * @return 分类ID
     */
    private Long extractCategoryId(Object data) {
        try {
            if (data instanceof Long) {
                return (Long) data;
            } else if (data instanceof Integer) {
                return ((Integer) data).longValue();
            } else if (data instanceof String) {
                return Long.valueOf(data.toString());
            } else {
                log.error("分类ID数据类型不支持: dataType={}, value={}", 
                        data.getClass().getSimpleName(), data);
                return null;
            }
        } catch (NumberFormatException e) {
            log.error("分类ID格式转换失败: data={}, error={}", data, e.getMessage());
            return null;
        }
    }

    /**
     * 从消息数据中提取产品同步消息
     * 
     * @param data 消息数据
     * @return 产品同步消息
     */
    private SuhuishouSyncMessageSender.SuhuishouProductSyncMessage extractProductSyncMessage(Object data) {
        try {
            if (data instanceof SuhuishouSyncMessageSender.SuhuishouProductSyncMessage) {
                return (SuhuishouSyncMessageSender.SuhuishouProductSyncMessage) data;
            } else if (data instanceof java.util.Map) {
                // 处理Map类型的数据（如LinkedHashMap）
                @SuppressWarnings("unchecked")
                java.util.Map<String, Object> map = (java.util.Map<String, Object>) data;
                
                SuhuishouSyncMessageSender.SuhuishouProductSyncMessage message = 
                    new SuhuishouSyncMessageSender.SuhuishouProductSyncMessage();
                
                // 从Map中提取categoryId和brandId
                Object categoryIdObj = map.get("categoryId");
                Object brandIdObj = map.get("brandId");
                
                if (categoryIdObj != null) {
                    if (categoryIdObj instanceof Number) {
                        message.setCategoryId(((Number) categoryIdObj).longValue());
                    } else if (categoryIdObj instanceof String) {
                        message.setCategoryId(Long.valueOf(categoryIdObj.toString()));
                    }
                }
                
                if (brandIdObj != null) {
                    if (brandIdObj instanceof Number) {
                        message.setBrandId(((Number) brandIdObj).longValue());
                    } else if (brandIdObj instanceof String) {
                        message.setBrandId(Long.valueOf(brandIdObj.toString()));
                    }
                }
                
                return message;
            } else {
                log.error("产品同步消息数据类型不支持: dataType={}, value={}", 
                        data.getClass().getSimpleName(), data);
                return null;
            }
        } catch (Exception e) {
            log.error("产品同步消息提取失败: data={}, error={}", data, e.getMessage());
            return null;
        }
    }
}
